﻿using System;
using System.Net.Mail;
using System.Web.UI.WebControls;
using Altairis.MailToolkit;

namespace SampleListManager {
    public partial class Default : System.Web.UI.Page {

        protected void Page_Load(object sender, EventArgs e) {
            // Populate dropdown with mailing list names
            if (!this.IsPostBack) {
                foreach (MailingListProvider list in MailingListManager.Lists) {
                    this.ListName.Items.Add(new ListItem(list.Description, list.Name));
                }
            }
        }

        protected void ButtonSubmit_Click(object sender, EventArgs e) {
            // Validate arguments
            if (!this.IsValid) return;

            // Parse e-mail address
            var email = new MailAddress(this.EmailAddressTextBox.Text);

            if (this.ListOperation.SelectedValue.Equals("SUB")) {
                // Subscribe
                var result = MailingListManager.Subscribe(this.ListName.SelectedValue, email);
                if (result) {
                    this.LiteralMessage.Text = string.Format("Request for subscription confirmation was sent to <code>{0}</code>.", email.Address);
                }
                else {
                    this.LiteralMessage.Text = string.Format("Address <code>{0}</code> is already in mailing list.", email.Address);
                }
            }
            else {
                // Remove
                var result = MailingListManager.Remove(this.ListName.SelectedValue, email);
                if (result) {
                    this.LiteralMessage.Text = string.Format("Request for removal confirmation was sent to <code>{0}</code>.", email.Address);
                }
                else {
                    this.LiteralMessage.Text = string.Format("Address <code>{0}</code> is not in mailing list.", email.Address);
                }
            }

            // Display result
            this.MultiViewPage.SetActiveView(this.ViewMessage);
        }

    }
}